package com.hlkj.warboot.configurer.util;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @Description: 使用JDK原生提供的net，无需其他jar包；HttpURLConnection是URLConnection的子类，提供更多的方法，使用更方便
 * @Author: 李星 lixing_java@163.com
 * @Date: 2020/3/15 17:00
 */
public class HttpHelperUtil {
    /*
     * @Description TODO http请求
     * @Author 李星
     * @Date 2020/3/15 17:03
     * @Param [urlParam, requestType: GET|POST]
     * @return java.lang.String
     *
     *  TODO get 调用
     *      String strRes = HttpHelper.sendRequestHttp("http://127.0.0.1:8080/llsc/hlkj/warboot/token/get", "GET", "name=lixing&age=29");
     *  // 接收
     *      @RequestMapping("get")
     *      @ResponseBody
     *      public Object get(@RequestParam(required = false) String name, @RequestParam(required = false) Integer age) {}
     *
     *  TODO post 调用
     *      JSONObject jsonObject = new JSONObject();
     *      jsonObject.put("name","LIXING");
     *      jsonObject.put("age",29);
     *      HttpHelper.sendRequestHttp("http://127.0.0.1:8080/llsc/hlkj/warboot/token/post", "POST", jsonObject);
     *  // 接收
     *      @RequestMapping("post")
     *      @ResponseBody
     *      public Object post(@RequestBody Demo demo ) {}
     */
    public static String sendRequestHttp(String requestUrl, String requestType, Object params) {
        HttpURLConnection httpURLConnection;
        BufferedReader bufferedReader;
        StringBuffer resultBuffer;
        try {
            if ("GET".equals(requestType) && params != null && StrUtil.isEffective(params.toString())) {
                requestUrl = requestUrl + "?" + params.toString(); // http://127.0.0.1:8080/warboot?pageNum=1&pageSize=10
            }
            URL url = new URL(requestUrl);
            //得到连接对象
            httpURLConnection = (HttpURLConnection) url.openConnection();
            //设置请求类型
            httpURLConnection.setRequestMethod(requestType);
            //设置请求需要返回的数据类型和字符集类型
            httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            //允许写出
            httpURLConnection.setDoOutput(true);
            //允许读入
            httpURLConnection.setDoInput(true);
            //不使用缓存
            httpURLConnection.setUseCaches(false);

            if ("POST".equals(requestType) && params != null && StrUtil.isEffective(params.toString())) {
                BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream()));
                bWriter.write(params.toString());
                bWriter.flush();
                bWriter.close();
            }
            //得到响应码
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                //得到响应流
                InputStream inputStream = httpURLConnection.getInputStream();
                //将响应流转换成字符串
                resultBuffer = new StringBuffer();
                String line;
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                while ((line = bufferedReader.readLine()) != null) {
                    resultBuffer.append(line);
                }
                return resultBuffer.toString();
            }

        } catch (Exception e) {
            System.out.println("sendRequestHttp出错：" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /*
     * @Description TODO https请求
     * @Author 李星
     * @Date 2020/3/15 17:03
     * @Param [urlParam, requestType: GET|POST]
     * @return java.lang.String
     */
    public static String sendRequestHttps(String requestUrl, String requestType, Object params) {
        HttpsURLConnection httpsURLConnection;
        BufferedReader bufferedReader;
        StringBuffer resultBuffer;
        try {
            if ("GET".equals(requestType) && params != null && StrUtil.isEffective(params.toString())) {
                requestUrl = requestUrl + "?" + params.toString(); // http://127.0.0.1:8080/warboot?pageNum=1&pageSize=10
            }
            URL url = new URL(requestUrl);
            //得到连接对象
            httpsURLConnection = (HttpsURLConnection) url.openConnection();
            //设置请求类型
            httpsURLConnection.setRequestMethod(requestType);
            //设置请求需要返回的数据类型和字符集类型
            httpsURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            //允许写出
            httpsURLConnection.setDoOutput(true);
            //允许读入
            httpsURLConnection.setDoInput(true);
            //不使用缓存
            httpsURLConnection.setUseCaches(false);

            if ("POST".equals(requestType) && params != null && StrUtil.isEffective(params.toString())) {
                BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(httpsURLConnection.getOutputStream()));
                bWriter.write(params.toString());
                bWriter.flush();
                bWriter.close();
            }
            //得到响应码
            int responseCode = httpsURLConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                //得到响应流
                InputStream inputStream = httpsURLConnection.getInputStream();
                //将响应流转换成字符串
                resultBuffer = new StringBuffer();
                String line;
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                while ((line = bufferedReader.readLine()) != null) {
                    resultBuffer.append(line);
                }
                return resultBuffer.toString();
            }

        } catch (Exception e) {
            System.out.println("sendRequestHttps出错：" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}
